﻿using Advantage.Data.Provider;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KitBuildingWF.DataAccess;
using KitBuildingWF.Models;
using KitBuildingWF.Views;
using KitBuildingWF.Controls;
using Microsoft.Reporting.WinForms;
using log4net;
using log4net.Config;


namespace KitBuildingWF
{
    public partial class MainWindow : Form 
    {
        private dbwindow popupdbwindow = null;
        private DataSet1 kitDataSet = new DataSet1();
        DataSet1TableAdapters.KitMainTableAdapter kitMainAdapter = new DataSet1TableAdapters.KitMainTableAdapter();
        DataSet1TableAdapters.KitBSTableAdapter kitBSAdapter = new DataSet1TableAdapters.KitBSTableAdapter();
        DataSet1TableAdapters.SingleKitTableAdapter singleKitAdapter = new DataSet1TableAdapters.SingleKitTableAdapter();
        DataSet1TableAdapters.StockTableAdapter stockAdapter = null;
        DataSet1TableAdapters.KitItemTableAdapter kitItemAdapter = new DataSet1TableAdapters.KitItemTableAdapter();
        DataSet1TableAdapters.StockItemTableAdapter stockItemAdapter = new DataSet1TableAdapters.StockItemTableAdapter(); // extended kit item table
        DataSet1TableAdapters.KitBRprtTableAdapter kitCRAdapter = new DataSet1TableAdapters.KitBRprtTableAdapter();
        // indicating if the kit item table has been filled
        private bool allKitItemsTableFilled = false;
        private bool isLoadingKitItemsTable = false;
        // loading indicator window
        private LoadingIndicator loadingIndicator = null;

        // logger
        log4net.ILog log = log4net.LogManager.GetLogger(typeof(MainWindow));



        public MainWindow()
        {
            InitializeComponent();
        }

        public DataSet1 GetDataSet()
        {
            return kitDataSet;
        }

        private void Init_BuildingSchedule()
        {
            //Load old build schedule
            try
            {
               // MessageBox.Show("start loading...");
                kitBSAdapter.Fill(kitDataSet.KitBS);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            buildScheduleDataGrid.AutoGenerateColumns = false;
            buildScheduleDataGrid.DataSource = kitDataSet.KitBS;
        }

        private void Init_KitContents()
        {
            kitMainAdapter.FillByKitCode(kitDataSet.KitMain);
            KitContentsDataGrid.AutoGenerateColumns = false;
            KitContentsDataGrid.DataSource = kitDataSet.KitMain;
        }

        private void Init_KitLineItems()
        {
            //singleKitAdapter.FillByKitCode(kitDataSet.SingleKit, "GK010");
            singleKitAdapter.Fill(kitDataSet.SingleKit);
            KitLineItemDataGrid.AutoGenerateColumns = false;
            KitLineItemDataGrid.DataSource = kitDataSet.SingleKit;

            kitDataSet.SingleKit.Clear();
           
        }

        private void Init_KitAllLineItems()
        {
            kitItemAdapter.FillByKitColumns(kitDataSet.KitItem, Config.GetSelectedBranch());
            stockItemAdapter.FillIncSuppliers(kitDataSet.StockItem, Config.GetSelectedBranch());
        }

        private void Init_CalculateReport()
        {
            CalculateReportDataGridView.AutoGenerateColumns = false;
            CalculateReportDataGridView.DataSource = kitDataSet.KitBRprt;
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Init Logger
            log4net.Config.BasicConfigurator.Configure();
            log.Info("Init logger");

            try
            {
                Console.WriteLine("Started");
                Init_BuildingSchedule();
                Console.WriteLine("Built Schedule");
                Init_KitContents();
                Console.WriteLine("Init Kit Contents");
                Init_KitLineItems();
                Console.WriteLine("Init Kit Line Items");
                Init_KitAllLineItems();
                Console.WriteLine("Init Kit All Line Items");
                Init_CalculateReport();
                Console.WriteLine("Init Calculate Report");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void adsConnection1_InfoMessage(object sender, Advantage.Data.Provider.AdsInfoMessageEventArgs e)
        {

        }

        private void adsDataAdapter1_RowUpdated(object sender, Advantage.Data.Provider.AdsRowUpdatedEventArgs e)
        {

        }


        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Switch to build schedule screen
        /// </summary>
        private void BuildScheduleBtn_Click(object sender, EventArgs e)
        {
            //StockDAO stockDao = DAOFactory.GetStockDAO("Native");
            //Stock testStock = stockDao.findById("0000130760");
            //MessageBox.Show(testStock.location.ToString());

            MainPanel.SelectedTab = BuildSchedulePanel;
        }

        /// <summary>
        /// Switch to kit contents panel
        /// </summary>
        private void KitContentsBtn_Click(object sender, EventArgs e)
        {
            MainPanel.SelectedTab = KitContentsPanel;   
            //KitDAO kitDao = DAOFactory.GetKitDAO("Native");
            //List<Kit> allKits = kitDao.findAll();
        }

        private void BuildScheduleAddBtn_Click(object sender, EventArgs e)
        {
            popupdbwindow = new dbwindow();

       
            popupdbwindow.SetDBDatasource(kitDataSet.KitMain);
            popupdbwindow.GetDataGridView().Columns["PKey"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["ItemDesc"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["AUXNOTE"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["KITITEM"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["ITEMQTY"].Visible = false;

            popupdbwindow.ShowDialog();


            // Retrieve the selected rows
            DataSet1.KitMainDataTable selectedKits = (DataSet1.KitMainDataTable)popupdbwindow.GetSelectedRowsAsTable();
            if (selectedKits != null && selectedKits.Count > 0)
            {
                foreach (DataSet1.KitMainRow selectedKit in selectedKits)
                {
                    DataSet1.KitBSRow newkitBSRow = kitDataSet.KitBS.NewKitBSRow();
                    newkitBSRow.KITCODE = selectedKit.KITCODE.Trim();
                    newkitBSRow.KITDESC = selectedKit.KITDESC.Trim();
                    newkitBSRow.BUILDNO = 1;
                    newkitBSRow.STOCK = 0;
                    newkitBSRow.BORDER = 0;
                    newkitBSRow.BUILDNOW = "N";
                    try
                    {
                        kitDataSet.KitBS.Rows.Add(newkitBSRow);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                    BuildScheduleSaveBtn.Enabled = true;
                }
            }
        }

        /// <summary>
        /// Add a new Kit
        /// </summary>
        private void KitContentsAddBtn_Click(object sender, EventArgs e)
        {
            // clear kit contence screen, and Switch to Kit Line item page
            //KitLineItemDataGrid.DataSource = null;
            KitCodeTextBox.Text = "";
            KitDescTextBox.Text = "";
            CapCodeTextBox.Text = "";

            kitDataSet.SingleKit.Clear();
            //KitLineItemDataGrid.DataSource = kitDataSet.SingleKit;

            MainPanel.SelectedTab = KitLineItems;
            KitLineItemMainPanel.Visible = true;
        }

        /// <summary>
        /// Return the Datagridview of kit building schedule view
        /// </summary>
        /// <returns>the building schedule datagridview</returns>
        public DataGridView GetBuildScheduleGridView()
        {
            return buildScheduleDataGrid;
        }

        private void buildScheduleDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        /// <summary>
        /// Remove a kit code from the building schedule
        /// </summary>
        private void BuildScheduleRemoveBtn_Click(object sender, EventArgs e)
        {
            List<int> rowsToDelete = new List<int>();

            InputDialog rdialog = new InputDialog("Cancel building this kit?");
            rdialog.ShowDialog();
            if (rdialog.GetResult() == false)
            {
                return;
            }
            
            
            if (buildScheduleDataGrid.SelectedCells.Count > 0){
                // remove all selected rows
                foreach (DataGridViewCell dgc in buildScheduleDataGrid.SelectedCells){
                    if (rowsToDelete.Contains(dgc.RowIndex) == false)
                    {
                        rowsToDelete.Add(dgc.RowIndex);
                        if (dgc.RowIndex < kitDataSet.KitBS.Rows.Count && dgc.RowIndex >= 0)
                        {
                            kitDataSet.KitBS.Rows[dgc.RowIndex].Delete();
                            BuildScheduleSaveBtn.Enabled = true;

                        }
                    }
                }
            }
        }

        /// <summary>
        /// Save all the changes made for kit building schedule
        /// </summary>
        private void BuildScheduleSaveBtn_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.KitBSTableAdapter kitBSAdapter = new DataSet1TableAdapters.KitBSTableAdapter();
            kitBSAdapter.Update(kitDataSet.KitBS);
            BuildScheduleSaveBtn.Enabled = false;
        }

        private void buildScheduleDataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            BuildScheduleSaveBtn.Enabled = true;
            BuildScheduleUndoBtn.Enabled = true;
            // MessageBox.Show(kitDataSet.Tables["kitBS"].Rows[0][2].ToString());
        }

        private void BuildScheduleNotesBtn_Click(object sender, EventArgs e)
        {
            MessageBox.Show(buildScheduleDataGrid.SelectedRows.Count.ToString());

        }

        /// <summary>
        /// Switch to Kit line items GUI
        /// </summary>
        private void KitContentsDataGrid_DoubleClick(object sender, EventArgs e)
        {
            MainPanel.SelectedTab = KitLineItems;
            KitLineItemMainPanel.Visible = true;
           
            //MessageBox.Show(kitDataSet.KitLineItems.Columns.Count.ToString());
            string selectedKit = null;

            if (KitContentsDataGrid.SelectedRows.Count > 0 && KitContentsDataGrid.SelectedRows != null)
            {

                selectedKit = KitContentsDataGrid.SelectedRows[0].Cells[0].Value.ToString().Trim();
                KitLineItemDataGrid.DataSource = kitDataSet.SingleKit;

                try
                {
                    singleKitAdapter.FillByKitCode(kitDataSet.SingleKit, selectedKit);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }


                KitCodeTextBox.Text = KitContentsDataGrid.SelectedRows[0].Cells[0].Value.ToString().Trim();
                KitDescTextBox.Text = KitContentsDataGrid.SelectedRows[0].Cells[2].Value.ToString().Trim();
                CapCodeTextBox.Text = KitContentsDataGrid.SelectedRows[0].Cells[1].Value.ToString().Trim();
            }

            KitLineItemSaveBtn.Enabled = false;
            
        }

        private void KitContentsItemDetailBtn_Click(object sender, EventArgs e)
        {
            // switch to kit line item screen
            KitContentsDataGrid_DoubleClick(new object(), new EventArgs());
        }

        /// <summary>
        /// add a new stock item into the kit.
        /// </summary>
        private void KitLineItemAddBtn_Click(object sender, EventArgs e)
        {
            // create a popup window for selecting stock item
            popupdbwindow = new dbwindow();
            popupdbwindow.Text = "Select stock items";

            kitItemAdapter.FillByKitColumns(kitDataSet.KitItem, Config.GetSelectedBranch());
            if (allKitItemsTableFilled == false)
            {
                loadingIndicator = new LoadingIndicator();

                if (isLoadingKitItemsTable == false)
                {
                    StockLoadingBGWorker.RunWorkerAsync();
                    isLoadingKitItemsTable = true;
                }
                loadingIndicator.ShowDialog();

            }

            if (allKitItemsTableFilled == false)
            {
                MessageBox.Show("Stock loading failed");
                return;
            }

            popupdbwindow.SetDBDatasource(kitDataSet.Tables["KITitem"]);

            popupdbwindow.GetDataGridView().Columns["BackOrder"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["LOCATION"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["Allocated"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["Stock_Out"].Visible = false;
            popupdbwindow.GetDataGridView().Columns["On_Order"].Visible = false;

            popupdbwindow.GetDataGridView().Columns["Name"].HeaderText = "Product Code";
            popupdbwindow.GetDataGridView().Columns["Title"].HeaderText = "Description";
            
            popupdbwindow.ShowDialog();
            
            // Add the stock item to build the new kit
            DataGridViewSelectedRowCollection selectedItems = popupdbwindow.GetSelectedRows();
            if (selectedItems != null && selectedItems.Count > 0)
            {
                foreach (DataGridViewRow selectedItem in selectedItems)
                {
                    DataSet1.SingleKitRow newkitRow = kitDataSet.SingleKit.NewSingleKitRow();
                    newkitRow.KITCODE = KitCodeTextBox.Text.Trim();
                    newkitRow.KITDESC = KitDescTextBox.Text.Trim();
                    newkitRow.CAPCODE = CapCodeTextBox.Text.Trim();
                    newkitRow.KITITEM = selectedItem.Cells[0].Value.ToString();
                    newkitRow.ITEMDESC = selectedItem.Cells[1].Value.ToString();
                    newkitRow.PKEY = newkitRow.KITCODE.Trim() + newkitRow.KITITEM.Trim();
                    kitDataSet.SingleKit.Rows.Add(newkitRow);
                    KitLineItemSaveBtn.Enabled = true;
                }
            }
        }

        private void KitCodeTextBox_TextChanged(object sender, EventArgs e)
        {
            // enable "Save" button if kit code changed
            KitLineItemSaveBtn.Enabled = true;
        }

        private void KitDescTextBox_TextChanged(object sender, EventArgs e)
        {
            // enable "Save" button if kit description changed
            KitLineItemSaveBtn.Enabled = true;
        }

        /// <summary>
        /// Save the kit
        /// if it is a new kit, added to the kit table
        /// </summary>
        private void KitLineItemSaveBtn_Click(object sender, EventArgs e)
        {
            //singleKitAdapter.Update(kitDataSet.SingleKit);

            KitLineItemSaveBtn.Enabled = false;

            if (KitCodeTextBox.Text.Trim().Length == 0)
            {
                MessageBox.Show("Update failed. \n\n Kit code is empty");
                return;
            }

            try
            {
                singleKitAdapter.Update(kitDataSet.SingleKit);
            }
            catch (Exception ex)
            {
                
                MessageBox.Show("Update failed" + "\n\n" +ex.Message);
                return;
            }

            if (kitDataSet.KitMain.Select("KITCODE = '" + KitCodeTextBox.Text.Trim() + "'").Length > 0)
            {
                // it's an existing kit, update
                MessageBox.Show("Kit Updated");
            }
            else
            {
                // new kit entered.
                MessageBox.Show("New Kit was added");

                // Reset the Kit contents view
                kitMainAdapter.FillByKitCode(kitDataSet.KitMain);
            }
        }

        /// <summary>
        /// Calculate the number of kits can be built from the available stock
        /// </summary>
        private void BuildScheduleCalculateBtn_Click(object sender, EventArgs e)
        {
            BuildKits bk = new BuildKits(kitDataSet);
            bk.AddKits(GenerateBuildingKits());
            bk.CalculateAll();
            UpdateBuildSchedule(bk.GetMappedPreparedKits());  // update building schedule view
            UpdateCalculateReport(bk.GetPreparedStocks());    // update calculate report view

            BuildScheduleSaveBtn.Enabled = true;
            BuildScheduleUndoBtn.Enabled = true;
            CReport_SaveBtn.Enabled = true;
        }

        /// <summary>
        /// Generate objects of requested kits in the building schedule screen
        /// </summary>
        /// <returns>all the kit objects</returns>
        private List<RequestedKit> GenerateBuildingKits()
        {
            List<RequestedKit> requestedKits = new List<RequestedKit>();

            // visit every row of the building schedule grid
            //foreach (DataGridViewRow row in buildScheduleDataGrid.Rows)
            foreach (DataSet1.KitBSRow row in kitDataSet.KitBS.Rows)
            {
               // if (row.Cells["KitCodeColumn"].Value != null)
                if (row.KITCODE != null)
                {
                     kitDataSet.SingleKit.Clear();

                    // populate the kit datatable 

                     singleKitAdapter.FillByKitCode(kitDataSet.SingleKit, row.KITCODE.Trim());


                    // igonre this item if there is no line item for this kit
                    // TODO: Log the error
                     if (kitDataSet.SingleKit.Rows.Count == 0)
                     {
                         continue;
                     }

                    KitLineItemDataGrid.DataSource = kitDataSet.SingleKit;
                    RequestedKit requestedKit = new RequestedKit();
                    List<KitLineItem> kitLineItems = new List<KitLineItem>();
                    

                    foreach (DataSet1.SingleKitRow lineItem in kitDataSet.SingleKit.Rows){
                        if (lineItem.KITITEM != null)
                        {
                            KitLineItem kitLineItem = new KitLineItem();
                            kitLineItem.itemCapitalCode = lineItem.KITITEM.Trim();
                            kitLineItem.itemDescription = lineItem.ITEMDESC.Trim();
                            kitLineItem.itemQty = Convert.ToInt32(lineItem.ITEMQTY);
                            kitLineItems.Add(kitLineItem);
                        }
                    }

                    requestedKit.contents = kitLineItems;
                    requestedKit.kitCode = row.KITCODE.Trim();
                    requestedKit.requestedNo =  Convert.ToInt32(row.BUILDNO);
                    requestedKit.kitDescription = row.KITDESC;

                    requestedKits.Add(requestedKit);
                }
            }

            return requestedKits;
        }

        private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config config = new Config();
            config.ShowDialog();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintDialog p1 = new PrintDialog();

            p1.ShowDialog();
        }

        /// <summary>
        /// Update building schedule with the prepared kits
        /// </summary>
        private void UpdateBuildSchedule(Dictionary<string, RequestedKit> preparedKits)
        {
            RequestedKit resultKit = null;

            // update build schedule view
            foreach (DataSet1.KitBSRow bsRow in kitDataSet.KitBS.Rows)
            {
                if (bsRow.KITCODE != null && preparedKits.ContainsKey(bsRow.KITCODE.Trim())){
                    resultKit = preparedKits[bsRow.KITCODE.Trim()];
                    // set the number of kits can be built from the available stock
                    bsRow.STOCK = resultKit.actualBuildNo;
                    
                    // set build Now checkbox
                    if (resultKit.actualBuildNo > 0)
                    {
                        bsRow.BUILDNOW = "Y";
                    }
                    else
                    {
                        bsRow.BUILDNOW = "N";
                    }

                    // set back order
                    bsRow.BORDER = bsRow.BUILDNO - bsRow.STOCK;
                }

                if (preparedKits.ContainsKey(bsRow.KITCODE.Trim()) == false)
                {
                    // the scheduled kit didn't prepared correctly. diable building
                    bsRow.SetBUILDNOWNull();
                }
            }

        }

        /// <summary>
        /// Update calculate report
        /// </summary>
        /// <param name="preparedStock">The prepared stock items in a list</param>
        private void UpdateCalculateReport(List<RequestedStock> preparedStock)
        {
            // clear the kit build calculate report view
            kitDataSet.KitBRprt.Clear();

            //Test code: add all the stock item to calculate report
            

            foreach (var resultStock in preparedStock){
                DataSet1.KitBRprtRow cReportRow = kitDataSet.KitBRprt.NewKitBRprtRow();
                cReportRow.STOCKCODE = resultStock.productCode;
                cReportRow.SUPPLIER = resultStock.s1Supplier;
                cReportRow.STOCKDESC = resultStock.description;
                cReportRow.STOCK_IN = resultStock.stockIn.ToString();
                cReportRow.PACKQTY = resultStock.s1PackQty;
                cReportRow.BRANCH = resultStock.location;

                int totalRequired = 0;
                // calculate required number of this stock
                foreach (var kidRequest in resultStock.kitRequestInfo) 
                {
                    totalRequired += kidRequest.requested;
                }

                //log.Info(resultStock.kitRequestInfo.Count);

                cReportRow.REQUIRE = totalRequired.ToString();
                if (resultStock.s1PackQty > 0 && resultStock.stockIn < totalRequired)
                {
                    cReportRow.ORDER = resultStock.s1PackQty * ((totalRequired - resultStock.stockIn) / resultStock.s1PackQty + 1);
                }
                else
                {
                    cReportRow.ORDER = 0;
                }

                //TODO set the primary key
                cReportRow.PKEY = "31102011" + cReportRow.STOCKCODE.Trim();
                cReportRow.BSNO = "31102011R004";

                kitDataSet.KitBRprt.Rows.Add(cReportRow);
            }

            
        }

        /// <summary>
        /// Remove a kit line item.
        /// </summary>
        private void KitLineItemRemoveBtn_Click(object sender, EventArgs e)
        {
            // check if there is a stock item selected
            if (KitLineItemDataGrid.SelectedCells.Count == 0)
            {
                // no item selected
                return;
            }

            // return if empty row was selected
            if (KitLineItemDataGrid.CurrentRow == null)
            {
                return;
            }

            //MessageBox.Show(KitLineItemDataGrid.CurrentRow.Index.ToString());

            InputDialog removeKitItemDialog = new InputDialog("Remove the stock item?");
            removeKitItemDialog.ShowDialog();

            if (removeKitItemDialog.GetResult() == true)
            {
                try
                {
                    kitDataSet.SingleKit.Rows[KitLineItemDataGrid.CurrentRow.Index].Delete();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }else{
                // user clicked "No"
                return;
            }

            KitLineItemSaveBtn.Enabled = true;
        }

        /// <summary>
        /// The exception handler for building schedule data grid
        /// </summary>
        private void buildScheduleDataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Exception != null && e.Context == DataGridViewDataErrorContexts.Commit)
            {
                MessageBox.Show("Error at row: " + e.RowIndex.ToString() + " :Kit code must be unique in build schedule.");
                return;
            }

            if (e.Context == DataGridViewDataErrorContexts.Parsing)
            {
                MessageBox.Show("Invalid value");
                return;
            }


            MessageBox.Show("Error at row: " + e.RowIndex.ToString() + "\n" + "Error type: "+ e.Context.ToString());
            //kitDataSet.KitBS.Rows[e.RowIndex][e.ColumnIndex] = 0;

        }

        /// <summary>
        /// Exception handler for kit line item data grid
        /// </summary>

        private void KitLineItemDataGrid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Error at row: " + e.RowIndex.ToString() + "\n" + "Error type: " + e.Context.ToString());
        }

        private void KitLineItemDataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            KitLineItemSaveBtn.Enabled = true;
            KitLineItemUndoBtn.Enabled = true;
        }

        private void KitLineItemUndoBtn_Click(object sender, EventArgs e)
        {
            kitDataSet.SingleKit.RejectChanges();
        }

        private void BuildScheduleUndoBtn_Click(object sender, EventArgs e)
        {
            kitDataSet.KitBS.RejectChanges();
            BuildScheduleUndoBtn.Enabled = false;
            
        }

        private void KitLineItemNoteBtn_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Remove a kit
        /// </summary>
        private void KitContentsRemoveBtn_Click(object sender, EventArgs e)
        {
            // get the kit code to be deleted
            string kitToDelete = KitContentsDataGrid.CurrentRow.Cells["KC_KitCodeColumn"].Value.ToString().Trim();
            singleKitAdapter.FillByKitCode(kitDataSet.SingleKit, kitToDelete);
            KitLineItemDataGrid.DataSource = kitDataSet.SingleKit;

            foreach (DataSet1.SingleKitRow row in kitDataSet.SingleKit)
            {
                row.Delete();
            }

            singleKitAdapter.Update(kitDataSet.SingleKit);
            kitMainAdapter.FillByKitCode(kitDataSet.KitMain);

            MessageBox.Show(kitToDelete + " deleted");
        }

        private void LoadAllKitItems()
        {

        }

        /// <summary>
        /// Loading stock items to the kititem table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StockLoadingBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            kitItemAdapter.FillByKitColumns(kitDataSet.KitItem, Config.GetSelectedBranch());

            /* test code
            for (int i = 0; i < 10000; i++)
            {
                Console.WriteLine(i.ToString());
            }
            */

        }

        private void StockLoadingBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            allKitItemsTableFilled = true;
            isLoadingKitItemsTable = false;
            if (loadingIndicator != null)
            {
                loadingIndicator.Close();
            }
        }

        /// <summary>
        /// show calculate report print view
        /// </summary>
        private void CReport_PrintBtn_Click(object sender, EventArgs e)
        {
            // fill the calculate report
            //kitCRAdapter.FillByAll(kitDataSet.KitBRprt);

            ReportViewForm rv = new ReportViewForm();

            rv.SetDataSource(kitDataSet);
            rv.ShowDialog();
        }

        /// <summary>
        /// Save calculate report
        /// </summary>
        private void CReport_SaveBtn_Click(object sender, EventArgs e)
        {
            kitCRAdapter.Update(kitDataSet.KitBRprt);
            CReport_SaveBtn.Enabled = false;
        }


    }
}
